package com.kunbo.cn.service.impl.system.user;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;
import com.bstek.uflo.process.assign.Entity;
import com.bstek.uflo.process.assign.PageQuery;
import com.kunbo.cn.app.util.Verificationcode;
import com.kunbo.cn.dao.system.user.DepartmentDao;
import com.kunbo.cn.dao.system.user.PositionDao;
import com.kunbo.cn.dao.system.user.UserDao;
import com.kunbo.cn.entity.EasyUiDataGrid;
import com.kunbo.cn.entity.system.user.Department;
import com.kunbo.cn.entity.system.user.User;
import com.kunbo.cn.service.base.EasyuiServiceImpl;
import com.kunbo.cn.service.system.user.UserService;
import com.kunbo.cn.util.date.SDate;
import com.kunbo.cn.util.db.DbQuerySql;
import com.kunbo.cn.util.encrypt.MD5Utils;
import com.kunbo.cn.util.retu.CommonResult;
import com.kunbo.cn.util.retu.ReturnBean;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private PositionDao positionDao;

	@Autowired
	private DepartmentDao departmentDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Resource
	private EasyuiServiceImpl easyUiDto;

	private Logger loger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Override
	public boolean delete(Integer id) {
		boolean result = true;
		try {
			userDao.delete(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result = false;
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public User check(String name, String password) {
		// TODO Auto-generated method stub
		User user = userDao.check(name, password);
		return user;
	}

	@Override
	public boolean save(User user) {
		user.setRegistration_date(SDate.getSystemDateToString());
		userDao.save(user);
		return true;
	}

	@Override
	public boolean update(User user) {
		userDao.save(user);
		return true;
	}

	@Override
	public EasyUiDataGrid getUserByDepartment(String department, String rows, String page) {
		// TODO Auto-generated method stub

		String sql = "";
		String count_sql = "";
		sql += "SELECT u.*, p.text position,d.text as dept,s.text as state FROM db_system_user_user u "
				+ " LEFT JOIN db_system_user_position p on u.position_id = p.id "
				+ " left join db_system_user_department d on u.department_id = d.id "
				+ " LEFT JOIN db_system_user_status s on u.status = s.id where 1= 1 ";
		sql += DbQuerySql.AEqualToB(" and u.department_id", department);
		sql += DbQuerySql.limit(page, rows);

		count_sql += "SELECT u.*, p.text position,d.text as dept,s.text as state FROM db_system_user_user u "
				+ " LEFT JOIN db_system_user_position p on u.position_id = p.id "
				+ " left join db_system_user_department d on u.department_id = d.id "
				+ " LEFT JOIN db_system_user_status s on u.status = s.id where 1= 1 ";
		count_sql += DbQuerySql.AEqualToB(" and u.department_id", department);

		return easyUiDto.getEasyUiDataGrid(sql, count_sql);
	}

	@Override
	public User findById(int id) {
		// TODO Auto-generated method stub
		return userDao.findById(id);
	}

	@Override
	public User findByActivitiUUID(String activiti_uuid) {
		// TODO Auto-generated method stub
		return userDao.findByActivitiUUID(activiti_uuid);
	}

	@Override
	public List<User> findByPositionId(int position_id) {
		return userDao.findByPositionId(position_id);
	}

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	private List<DepTmp> getDepartments() {
		List<DepTmp> ret = new ArrayList<DepTmp>();
		List<Department> xxx = departmentDao.findAll();
		for (Department d : xxx) {
			ret.add(new DepTmp(d.getId(), d.getParent_id(), d.getText(), false, null));
		}
		return ret;
	}

	private List<DepTmp> getUsers() {
		List<DepTmp> ret = new ArrayList<DepTmp>();
		List<User> users = userDao.findAll();
		for (User u : users) {
			ret.add(new DepTmp(u.getId(), u.getDepartment_id(), u.getActual_name(), true, null));
		}
		return ret;
	}
//	private List<DeptDto> getChildsManyGroupDepTmp(List<Map<String, Object>> list,int pid)
//	{  
//		List<DeptDto> arr = new ArrayList<DeptDto>();  
//		List<Map<String, Object>> groupLidt = new ArrayList<Map<String, Object>>();
//		DeptDto dd = new DeptDto();
//		List<UserDto> userArr = new ArrayList<UserDto>();
//		for(Map<String, Object> location : list){
//			loger.info("pid=="+pid);
//			loger.info("deptid=="+location.get("department_id"));
//		    if(pid == (int)location.get("parent_id")){
//		    	dd.setDeptId((Integer)location.get("department_id"));
//		    	dd.setDeptName((String)location.get("text"));
//		    	dd.setParentId(pid);
//		    	UserDto ud = new UserDto();
//		    	ud.setId((Integer)location.get("id"));
//		    	ud.setUserName((String)location.get("actual_name"));
//		    	userArr.add(ud);
//		    	dd.setUserlist(userArr);
//		    	groupLidt.add(location);
//		    	dd.setDeptDtoList(getChildsManyGroupDepTmp(groupLidt, (Integer)location.get("department_id")));   
//		        arr.add(dd);   
//		    }  
//		}  
//		//System.out.println(arr.toString());
//		loger.info("dd = "+Json.toJson(dd));
//		return arr;  
//	} 

	private List<DepTmp> getChildsManyGroupDepTmp(List<DepTmp> list, int pid) {
		List<DepTmp> arr = new ArrayList<DepTmp>();
		for (DepTmp location : list) {
			if (pid == location.getParent_id()) {
				location.setChildren(getChildsManyGroupDepTmp(list, location.getId()));
				arr.add(location);
			}
		}
		return arr;
	}

	@Override
	public List<DepTmp> getEasyUiTreeDepAndUser() {
		List<DepTmp> ret = new ArrayList<DepTmp>();
		List<DepTmp> list1 = getDepartments();
		List<DepTmp> list2 = getUsers();
		for (DepTmp d : list1) {
			ret.add(d);
		}
		for (DepTmp d : list2) {
			ret.add(d);
		}
		ret = getChildsManyGroupDepTmp(ret, 0);
		return ret;
	}

	@Override
	public ReturnBean isUserExist(int id) {
		// TODO Auto-generated method stub
		User user = findById(id);
		if (user == null)
			return new ReturnBean(false, "用户不存在");
		else
			return new ReturnBean(true, "用户存在");
	}

	@Override
	public void page(PageQuery<Entity> query) {
		int current = query.getPageIndex() - 1;
		int size = query.getPageSize();
		Pageable page = new PageRequest(current, size);
		Page<User> user = userDao.page(page);
		List<Entity> lt = new ArrayList<Entity>();
		for (User u : user.getContent()) {
			Entity et = new Entity(String.valueOf(u.getId()), u.getName());
			lt.add(et);
		}
		query.setId("1");
		query.setName("所有用户");
		query.setPageIndex(current + 1);
		query.setPageSize(size);
		query.setTree(false);
		query.setResult(lt);
		query.setRecordCount(userDao.findAll().size());
	}

	@Override
	public void page1(PageQuery<Entity> query) {
		int current = query.getPageIndex();
		int size = query.getPageSize();
		List<User> user = userDao.findByPositionId(9);
		List<Entity> lt = new ArrayList<Entity>();
		for (User u : user) {
			Entity et = new Entity(String.valueOf(u.getId()), u.getName());
			lt.add(et);
		}
		query.setId("1");
		query.setName("所有用户");
		query.setPageIndex(current + 1);
		query.setPageSize(size);
		query.setTree(false);
		query.setResult(lt);
		query.setRecordCount(user.size());
	}

	// 获取所有用户列表
	public List<Map<String, Object>> getAllUser() {
		String sql = "SELECT db_system_user_user.id, db_system_user_user.actual_name,"
				+ " db_system_user_user.department_id,db_system_user_department.text,"
				+ " db_system_user_department.parent_id FROM db_system_user_user LEFT JOIN "
				+ " db_system_user_department ON db_system_user_department.id = db_system_user_user.department_id";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		System.out.println(list);
		System.out.println(list.size() + "======================");
		return list;
	}

	@Override
	public User findByName(String name) {
		return userDao.findByName(name);
	}

	@Override
	public User findByActual_name(String personLiable) {
		// TODO Auto-generated method stub
		if (userDao.findByActual_name(personLiable).size() == 0) {
			return null;
		} else {
			return userDao.findByActual_name(personLiable).get(0);
		}

	}

	@Override
	public Boolean login(String userName, String password) {
		// TODO Auto-generated method stub
		String sql = "select * from db_system_user_user where name = '" + userName + "' and password = '" + password
				+ "'";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		if (list != null && list.size() > 0)
			return true;
		else
			return false;
	}

	@Override
	public String validatePhone(String phone) {
		// TODO Auto-generated method stub
		try {
			return Verificationcode.sendMsg(phone);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Boolean setNewPassword(String phone, String password) {
		// TODO Auto-generated method stub
		String sql = "update db_system_user_user set password = '" + password + "' where phone_call = '" + phone + "'";
		int i = jdbcTemplate.update(sql);
		if(i > 0 )
			return true;
		else
		    return false;
	}

	@Override
	public Boolean setPassword(String oldPassword, String newPassword) {
		// TODO Auto-generated method stub
		String sql = "update db_system_user_user set password = '" + newPassword + "' where password = '" + oldPassword + "'"; 
		int i = jdbcTemplate.update(sql);
		if(i > 0 )
			return true;
		else
		    return false;
	}

	@Override
	public Boolean setNewPhone(String oldPhone, String newPhone) {
		// TODO Auto-generated method stub
		String sql = "update db_system_user_user set phone_call = '" + newPhone + "' where phone_call = '" + oldPhone + "'"; 
		int i = jdbcTemplate.update(sql);
		if(i > 0 )
			return true;
		else
		    return false;
	}

	@Override
	public Boolean updatePassword(Integer id, String password) {
		// TODO Auto-generated method stub
		String sql = "update db_system_user_user set password = '" + MD5Utils.md5(password) + "' where id = " + id;
		int i = jdbcTemplate.update(sql);
		if(i > 0 )
			return true;
		else
		    return false;
	}

	@Override
	public Boolean updatePhone(String oldPhone, String newPhone) {
		// TODO Auto-generated method stub
		String sql = "update db_system_user_user set phone_call = '" + newPhone + "' where phone_call = " + oldPhone;
		int i = jdbcTemplate.update(sql);
		if(i > 0 )
			return true;
		else
		    return false;
	}

	@Override
	public Boolean setPasswordByPhone(String phone, String password) {
		// TODO Auto-generated method stub
		String sql = "update db_system_user_user set password = '" + MD5Utils.md5(password) + "' where phone_call = " + phone;
		int i = jdbcTemplate.update(sql);
		if(i > 0 )
			return true;
		else
		    return false;
	}

}
